package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    //--1--图片上传
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile==null || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //--上传图片到minio
        String fileName= UUID.randomUUID().toString().replace("-","");

        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId=null;
        try {
            fileId=fileStorageService.uploadHtmlFile("",fileName+postfix,multipartFile.getInputStream());
            log.info("上传图片到MinIO中，fileId:{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl-上传文件失败");
        }
        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //4.返回结果

        return ResponseResult.okResult(wmMaterial);
    }

    //--2--素材列表查询
    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        dto.checkParam();  //检查分页参数

        IPage page = new Page(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //1、是否收藏
        if (dto.getIsCollection()!=null && dto.getIsCollection()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //2、匹配用户
        lambdaQueryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        //3、时间顺序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        page=page(page,lambdaQueryWrapper);

        //4、返回结果
        ResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }


    //--3--素材--图片删除
    @Override
    public ResponseResult delPicture(Integer id) {
        //--判空
        WmMaterial material = getById(id);
        if (material==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);//501,"无效参数"
        }
        if (material.getUrl()==null || material.getUrl()==""){
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);//数据不存在
        }

        //--删除
        try {
            fileStorageService.delete(material.getUrl());
            removeById(id);
        } catch (Exception e) {
            ResponseResult.errorResult(501,"文件删除失败");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //--4-1-素材--图片取消收藏
    @Override
    public ResponseResult cancelCollect(Integer id) {
        short isCollection=0;
        return on_cancel(isCollection,id);
    }

    //--4-2-素材--图片收藏
    @Override
    public ResponseResult onCollect(Integer id) {
        short isCollection=1;
        return on_cancel(isCollection,id);
    }

    public ResponseResult on_cancel(short isCollection,Integer id){
        //--判空
        WmMaterial material = getById(id);
        if (material==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);//501,"无效参数"
        }

        //--收藏：1   取消：0
        material.setIsCollection(isCollection);
        updateById(material);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
